package org.zhou.demo1;

import java.io.*;
import java.util.List;

public class LogFileOperateImpl implements LogFileOperateApi {
    private String logFilePathName = "03-adapter/adapter-log.txt";

    public LogFileOperateImpl(String logFilePathName) {
        if (logFilePathName == null || logFilePathName.trim().length() == 0) {
            return;
        }

        this.logFilePathName = logFilePathName;
    }


    @Override
    public void writeLogFile(List<LogModel> logModels) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(this.logFilePathName)));
            oos.writeObject(logModels);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<LogModel> readLogFile() {
        List<LogModel> logModels = null;

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(this.logFilePathName)));
            logModels = (List<LogModel>) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return logModels;
    }
}
